import React, { useEffect, useState, useRef } from 'react';
import {
  Button,
  InfiniteScroll,
  List,
  DotLoading,
  SearchBar,
  PullToRefresh,
  Empty,
} from 'antd-mobile';
import styles from './index.less';
import { doFetch } from '@/utils/doFetch';
import { FilterFilled } from '@ant-design/icons';
import { useAsyncEffect } from 'ahooks';
import { cloneElement } from 'react';

function useDidUpdateEffect(fn, inputs) {
  const didMountRef = useRef(false);
  useAsyncEffect(async () => {
    if (didMountRef.current) await fn();
    else didMountRef.current = true;
  }, inputs);
}

export default (props) => {
  const {
    actionRef, //表格动作
    formRef, //表单Ref
    rowKey, // key
    columns = [], //columns
    style, //style
    path, //接口地址
    extraparams, //额外参数
    pageSize, //修改默认pageSize
    pagination, //分页设置
    activeTabKey, //激活的tabKey 拖拽表格唯一标识使用 其他情况用不到
    refreshDep, //依赖刷新 （已废弃）
    resizeable = true,
    iscurrent = true,
    children,
  } = props;

  const [data, setData] = useState([]);
  const [hasMore, setHasMore] = useState(true);
  const [pageinfo, setpageinfo] = useState({
    pageIndex: 1,
    pageSize: 8,
  });
  const [searchparams, setsearchparams] = useState({});
  const [open, setopen] = useState(false);

  async function getdata(pageinfo) {
    const append = await doFetch({
      url: path,
      params: {
        ...pageinfo,
        ...extraparams,
        ...searchparams,
      },
    });
    const dataes = append?.data?.page?.list ?? append?.data?.dataList ?? [];
    setData((val) => [...val, ...dataes]);
    return append?.data?.page ?? { hasNextPage: false };
  }
  //加载更多数据
  async function loadMore() {
    await setpageinfo((s) => ({
      ...s,
      pageIndex: s?.pageIndex + 1,
    }));
  }

  //刷新
  async function reFresh() {
    //页码重置 数据清空
    await setpageinfo((s) => ({
      ...s,
      pageIndex: 1,
    }));
    await setData([]);
  }

  //额外参数改变后重置
  useAsyncEffect(async () => {
    await reFresh();
  }, [extraparams]);

  //分页信息改变后调用数据接口
  useDidUpdateEffect(async () => {
    let page = await getdata(pageinfo);
    setHasMore(page?.hasNextPage);
  }, [pageinfo]);

  return (
    <>
      <div className={styles.header}>
        <div className="center">
          <div className={styles.left}>
            <div
              className="center"
              style={{ width: 30, height: 30, marginRight: 8 }}
              onClick={() => {
                setopen(!open);
              }}
            >
              <FilterFilled />
            </div>

            <SearchBar
              style={{ flex: 1 }}
              onChange={(val) => {
                setsearchparams((s) => ({
                  ...s,
                  userName: val,
                }));
              }}
            />
          </div>
          <div className={styles.right}>
            <Button size="small" color="primary" onClick={reFresh}>
              搜索
            </Button>
          </div>
        </div>
        <div className={styles.searchbar} style={{ height: open ? '40vh' : 0 }}>
          <div></div>
        </div>
      </div>
      {data.length > 0 ? (
        <PullToRefresh
          onRefresh={async () => {
            await reFresh();
          }}
        >
          {data.map((item, index) => cloneElement(children, { item, columns }))}
          <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
        </PullToRefresh>
      ) : (
        <PullToRefresh
          onRefresh={async () => {
            await reFresh();
          }}
        >
          <Empty
            style={{ padding: '64px 0' }}
            imageStyle={{ width: '30vw' }}
            description="暂无数据"
          />
        </PullToRefresh>
      )}
    </>
  );
};
